package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;

public class EditPackingSlipShippingAddressAction extends ChipTrackAction
{
    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
        // Extract attributes and parameters we will need
        //AddressForm addressForm = (AddressForm) form;
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        PackingSlipForm packingSlipForm = ( PackingSlipForm ) session.getAttribute ( "packingSlipForm" );

        User user = (User)session.getAttribute (SessionKeys.USER_KEY);
        if (user == null)
        {
            request.setAttribute ( "closeWindowAfterSessionExp", "true" );
            return ( mapping.findForward("showShippingAddress") );
        }

		// Validate the request parameters specified by the user
		ActionErrors errors = new ActionErrors();
        HashMap errorsTemp = new HashMap();
        if( "AddShippingAddress".equals(action) )
        {
            packingSlipForm.setNewShippingAddress( new Address() );
            return (mapping.findForward("showShippingAddress"));
        }
        else if( "SaveShippingAddress".equals(action) )
        {
            DBTransaction dbTransaction = null;
            boolean success = false;
            Address newShippingAddress  = packingSlipForm.getNewShippingAddress();
            if( newShippingAddress != null)
            {
                    packingSlipForm.setShippingAddressObject( newShippingAddress );
            }
            try
            {
                // Start transaction
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                //int customerId = NewSalesOrderDAO.getCustomerID( dbTransaction, packingSlipForm.getSalesOrderId() + "" );
                int customerId = -1;
                if( packingSlipForm.getOdmId() > 0 )
                {
                    customerId = packingSlipForm.getOdmId();
                }
                else
                {
                    customerId = NewSalesOrderDAO.getCustomerID( dbTransaction, packingSlipForm.getSalesOrderId() + "" );
                }


                //Insert the address details in the Address Table and get addressId
                int addressId = SalesOrderDAO.saveShippingAddress(dbTransaction,
                                    newShippingAddress.getAddress1(),
                                    newShippingAddress.getAddress2(),
                                    newShippingAddress.getAddress3(),
                                    newShippingAddress.getAddress4(),
                                    newShippingAddress.getCity(),
                                    newShippingAddress.getState(),
                                    newShippingAddress.getZipCode(),
                                    newShippingAddress.getCountry(),
                                    newShippingAddress.getPhoneNumber(),
                                    newShippingAddress.getFaxNumber(),
                                    newShippingAddress.getEmail(),
                                    newShippingAddress.getContactPerson(),
                                    newShippingAddress.getCellNumber(),
                                    newShippingAddress.getTagName() );

                //System.out.println("------------------EditPSShipAddAction--Add1 = " + newShippingAddress.getAddress1() + " customerId = " + customerId + " addressId = " + addressId );
                // To insert the contact person details in address contact person table
                if( !( "".equals( newShippingAddress.getContactPerson() ) ) && !( Constants.SALES_INTEGRATION_TYPE_GREAT_PLAINS.equals( ConfigManager.getSalesIntegrationType() ) ) )
                {
                    CustomerDAO.insertContactPerson (dbTransaction, addressId, newShippingAddress.getContactPerson(), newShippingAddress.getPhoneNumber(),newShippingAddress.getCellNumber(), newShippingAddress.getFaxNumber() , newShippingAddress.getEmail(), false , false, false, false, false, "", "Address", false, false);
                }
                //Insert the values in the customer shippingtable
                CustomerDAO.updateCustomerAddressTable( dbTransaction, customerId, addressId, "Shipping");
                success = true;
                session.setAttribute( "newPSShippingAddressId", Integer.toString( addressId ) );

                ArrayList shippingList = ( ArrayList ) session.getAttribute("psShippingAddresses");
                String addrStr = "";
                if( ( newShippingAddress.getContactPerson() != null )  && ( newShippingAddress.getContactPerson().trim().length() != 0 ) )
                {
                    shippingList.add( new LabelValueBean( newShippingAddress.getContactPerson(), Integer.toString(addressId ) ) );
                }
                if( ( newShippingAddress.getAddress1() != null ) && ( newShippingAddress.getAddress1().trim().length() != 0 ) )
                {
                    shippingList.add( new LabelValueBean( newShippingAddress.getAddress1(), Integer.toString( addressId ) ) );
                }
                if( ( newShippingAddress.getAddress2() != null )  && ( newShippingAddress.getAddress2().trim().length() != 0 ) )
                {
                    shippingList.add( new LabelValueBean( newShippingAddress.getAddress2() + "," , Integer.toString( addressId ) ) );
                }
                if( ( newShippingAddress.getAddress3() != null ) && ( newShippingAddress.getAddress3().trim().length() != 0 ) )
                {
                   shippingList.add( new LabelValueBean( newShippingAddress.getAddress3(), Integer.toString( addressId ) ) );
                }
                if( ( newShippingAddress.getAddress4() != null )  && ( newShippingAddress.getAddress4().trim().length() != 0 ) )
                {
                   shippingList.add( new LabelValueBean( newShippingAddress.getAddress4() + "," , Integer.toString( addressId ) ) );
                }
                if( ( newShippingAddress.getCity() != null )  && ( newShippingAddress.getCity().trim().length() != 0 ) )
                {
                    shippingList.add( new LabelValueBean( newShippingAddress.getCity() , Integer.toString( addressId ) ) );
                }
                if( ( newShippingAddress.getState() != null )  && ( newShippingAddress.getState().trim().length() != 0 ) )
                {
                    if( addrStr.trim().length() != 0 )
                        addrStr = addrStr + " ,"+newShippingAddress.getState();
                    else
                        addrStr=newShippingAddress.getState();
                }
                if( ( newShippingAddress.getZipCode() != null )  && ( newShippingAddress.getZipCode().trim().length() != 0 ) )
                {
                    if( addrStr.trim().length() !=0 )
                        addrStr = addrStr + " ,"+newShippingAddress.getZipCode();
                    else
                        addrStr=newShippingAddress.getZipCode();
                }
                if( ( newShippingAddress.getCountry() != null )  && ( newShippingAddress.getCountry().trim().length() != 0 ) )
                {
                    if( addrStr.trim().length() != 0 )
                        addrStr = addrStr + " ,"+newShippingAddress.getCountry();
                    else
                        addrStr=newShippingAddress.getCountry();
                }

                if(addrStr.trim().length() != 0 )
                    shippingList.add( new LabelValueBean(addrStr,Integer.toString( addressId )) );

                shippingList.add(new LabelValueBean("    " , Integer.toString( addressId )));

                session.setAttribute("psShippingAddresses",shippingList);
            }
            catch (ScalarException se)
            {
                errorsTemp.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save Packing Slip Address." );
                errorsTemp.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Shipping Details ");
                session.setAttribute( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                // Rollback or Commit the Transaction
                if (success == true)
                    dbTransaction.commit();
                else
                    dbTransaction.rollback();

            }
            if(!errorsTemp.isEmpty())
            {
                request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
            }
            return mapping.findForward("showShippingAddress");
        }
        /*else if( request.getParameter ( "shippingAddressId" ) != null )
        {
            int shippingAddressId = -1;

            try{
                shippingAddressId = Integer.parseInt( request.getParameter ( "shippingAddressId" ) );
            }catch( NumberFormatException nfe ){};

            packingSlipForm.setNewShippingAddress( NewPackingSlipDAO.loadShippingAddressDetails( null, shippingAddressId  ) );

            return mapping.findForward("showShippingAddress");
        } */

        return null;
    }
}
